package it.polimi.digitalstate.webbeans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import it.polimi.digitalstate.dto.PartyDTO;
import it.polimi.digitalstate.manager.AuthenticationManagerLocal;
import it.polimi.digitalstate.manager.PartyManagerLocal;
import it.polimi.digitalstate.persist.SuperEntityManagerException;
import it.polimi.digitalstate.persist.UniquePartyNameException;
import it.polimi.digitalstate.persist.UniquePartySymbolException;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.hibernate.validator.constraints.NotEmpty;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
/**
 * This webbean permit to perform the party creation
 *
 */
@ManagedBean(name="partyCreationBean")
@RequestScoped
public class PartyCreationBean {
	@EJB
	PartyManagerLocal ejb_partymanager;
	@EJB
	AuthenticationManagerLocal ejb_user;
	
	private UIComponent text1;
	private UIComponent text2;
	private UIComponent imgUploader;
	private UIComponent pdfUploader;

	private PartyDTO party= new PartyDTO();

	private UploadedFile file;

	private UploadedFile pdffile;
	
	
	public UIComponent getImgUploader() {
		return imgUploader;
	}

	public void setImgUploader(UIComponent imgUploader) {
		this.imgUploader = imgUploader;
	}

	public UIComponent getPdfUploader() {
		return pdfUploader;
	}

	public void setPdfUploader(UIComponent pdfUploader) {
		this.pdfUploader = pdfUploader;
	}
	
    public UploadedFile getFile() {
        return file;
    }
 
    public void setFile(UploadedFile file) {
        this.file = file;
    }
    
	public String getName(){
		return party.getName();
	}
	
	public String getSymbol(){
		return party.getSymbol();
	}
	
	public String getProgram(){
		return party.getProgram();
	}
	
	public void setName(String name){
		 party.setName(name);
	}
	
	public void setSymbol(String symbol){
		party.setSymbol(symbol);
	}
	
	public void setProgram(String program){
		party.setProgram(program);
	}
	private String getFileExtension(UploadedFile f){
		return f.getFileName().substring(
                f.getFileName().lastIndexOf('.'));
	}
	/**
	 * This method will make the party persistent in the database, or it will show the right error message
	 * depending on the violated constraint
	 * @return
	 */
	public String  commitNewParty(){
		/*
		 * check if the user is uploading the right files
		 */
		try{
			if(!file.getFileName().equalsIgnoreCase("")){
				if(!getFileExtension(file).equalsIgnoreCase(".jpg") && !getFileExtension(file).equalsIgnoreCase(".png")){
					showMessage(imgUploader, "You can only upload img or jpg files");
					return "#";
				}
			}else{
				showMessage(imgUploader, "You should upload an image as symbol of your party");
				return "#";
			}
			System.out.println(getFileExtension(pdffile));
			if(!pdffile.getFileName().equalsIgnoreCase("")){
				if(!getFileExtension(pdffile).equalsIgnoreCase(".pdf")){
					showMessage(pdfUploader,"You can only upload pdf files");
					return "#";
				}
			}else{
				showMessage(pdfUploader, "You should upload your cv");
				return "#";
			}
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
		    String imgname = fmt.format(new Date())
		            + getFileExtension(file);
		    party.setSymbol(imgname);
		    String pdfname = fmt.format(new Date())
		            + getFileExtension(pdffile);
		    party.setSymbol(imgname);
		    if(ejb_partymanager.canCreateParty(ejb_user.getLoggedCitizen())){
		    		ejb_partymanager.createNewParty(party,ejb_user.getLoggedCitizen(),pdfname);
		    		upload(imgname,true);
		    		upload(pdfname,false);
		    		return "partycorrectlycreated?faces-redirect=true";	
		    }else{
		    	return "partycreationerror?faces-redirect=true";	
		    }
		}catch(UniquePartyNameException ex){
			showMessage(text1,"This name already exists");
		}catch(UniquePartySymbolException ex){
			showMessage(text2,"This symbol already exists");
		}catch(SuperEntityManagerException ex){
			
		}
		return "#";
	}
	private void showMessage(UIComponent component, String str_message){
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,str_message,str_message);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(component.getClientId(context), message);
	}
	public void setParty(PartyDTO party){
		this.party=party;
	}
	public PartyDTO getParty(){
		return party;
	}

	public UIComponent getText1() {
		return text1;
	}

	public void setText1(UIComponent text1) {
		this.text1 = text1;
	}

	public UIComponent getText2() {
		return text2;
	}

	public void setText2(UIComponent text2) {
		this.text2 = text2;
	}
	private void fileUpload(String name, boolean imgsymbol) throws IOException {
	    String path = FacesContext.getCurrentInstance().getExternalContext()
	            .getRealPath("/");
	    File f;
	    if(imgsymbol)
	    f = new File(path + "partysymbols/" + name);
	    else
	    	f = new File(path + "cvs/" + name);	
	    InputStream is;
	    if(imgsymbol)
	    	is= file.getInputstream();
	    else
	    	is=pdffile.getInputstream();
	    OutputStream out = new FileOutputStream(f);
	    byte buf[] = new byte[1024];
	    int len;
	    while ((len = is.read(buf)) > 0)
	        out.write(buf, 0, len);
	    is.close();
	    out.close();
	}
	private void upload(String name, boolean imgsymbol) {
        if(file != null) {
            try {
				fileUpload(name, imgsymbol);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }

	public UploadedFile getPdffile() {
		return pdffile;
	}

	public void setPdffile(UploadedFile pdffile) {
		this.pdffile = pdffile;
	}
}
